﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using QuickTestApplication = QuickTest.Application;

namespace TestExtensions
{
    public class TestRepository : IDisposable
    {
        #region Constants

        private const string BASE_DIRECTORY = @"C:\Program Files\HP\QuickTest Professional\Tests\";

        #endregion

        #region Variables

        private bool _disposed;
        private QuickTestApplication _application;

        #endregion

        #region Constructors

        public TestRepository()
        {
            _disposed = false;
            _application = new QuickTestApplication();
            while (true)
            {
                try
                {
                    _application.Launch();
                    break;
                }
                catch (COMException) // keep trying until the RPC server is ready
                {
                    continue;
                }
            }
            while (!_application.Launched) ;
            _application.Visible = true;
        }

        ~TestRepository()
        {
            Dispose(false);
        }

        #endregion

        #region Properties

        public Test CurrentTest { get; private set; }

        #endregion

        #region Methods

        public Test LoadTest(string testPath)
        {
            _application.Open(testPath);
            //_application.Open(GetTestPath(testPath));
            CurrentTest = new Test(_application.Test, testPath);
            return CurrentTest;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Dispose of all managed resources.
                }

                // Dispose of all nonmanaged resources:
                if (CurrentTest != null)
                {
                    CurrentTest.Dispose();
                }
                _application.Quit();
                _application = null;

                Process.GetProcessesByName("QTPro").ToList().ForEach(ps => ps.Kill());
                Process.GetProcessesByName("QTAutomationAgent").ToList().ForEach(ps => ps.Kill());

                _disposed = true;
            }
        }

        //internal static string GetTestPath(string testName)
        //{
        //    try
        //    {
        //        return new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.GetDirectories(testName).First().FullName;
        //    }
        //    catch (Exception)
        //    {
        //        // Test does not exist.
        //        return null;
        //    }
        //}

        #endregion
    }
}